package com.jrfid.smartcabinet.demo.ui.login.account

import android.app.Application
import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import androidx.navigation.navOptions
import com.blankj.utilcode.util.ToastUtils
import com.jrfid.smartcabinet.demo.R
import com.jrfid.smartcabinet.demo.base.BaseViewModel
import com.jrfid.smartcabinet.demo.db.AppDatabase

class LoginByAccountViewModel(application: Application, navController: NavController) : BaseViewModel(application, navController) {

    val account = ObservableField("")
    val password = ObservableField("")

    fun onClickLogin(view: View) {
        val a = account.get()
        if (a.isNullOrEmpty()) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_account_hint))
            return
        }
        val p = password.get()
        if (p.isNullOrEmpty()) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_password_hint))
            return
        }
        val info = AppDatabase.instance.getAccountInfoDao().findByAccount(a)
        if (info == null) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_account_not_exist))
            return
        }
        if (p != info.password) {
            ToastUtils.showShort(getString(R.string.text_login_by_account_password_error))
            return
        }
        ToastUtils.showShort(getString(R.string.text_login_successfully))
        navController.navigate(R.id.action_loginFragment_to_homeFragment)
    }
}